package fm.dongman.animefm.view.fragment;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import fm.dongman.animefm.R;
import fm.dongman.animefm.contractlib.IModel;
import fm.dongman.animefm.contractlib.contract.MyContract;
import fm.dongman.animefm.contractlib.contract.SheetInfoContract;
import fm.dongman.animefm.view.activity.SingleActivity;
import fm.dongman.animefm.view.adapter.UsedAdapter;
import fm.dongman.animefm.view.listener.LoadMoreRecyclerOnScrollListener;
import fm.dongman.animefm.view.transform.GlideRoundTransform;
import fm.dongman.animefm.view.util.ActivityHelper;
import fm.dongman.animefm.view.util.ShareHelper;
import fm.dongman.animefm.view.util.ToastHelper;
import fm.dongman.modellib.StaticArea.Injection;
import fm.dongman.modellib.model.ComicModel;
import fm.dongman.modellib.model.SheetModel;
import fm.dongman.presenterlib.presenter.SheetInfoPresenter;

/**
 * @author alex 2017.10.25
 * @description 专题（官方漫单）详情页
 */
public class SheetTopicDetailsFragment extends BaseFragment implements SheetInfoContract.ISheetInfoView {

    private ImageButton mIbBack;    //返回按钮
    private ImageButton mIbShare;   //分享按钮

    private TextView mTvTitle;      //标题
    private TextView mTvDesc;       //描述信息
    private TextView mTvInfo;       //相关信息
    private View mTintMask;
    private CollapsingToolbarLayout mCollapsingToolbarLayout;
    private TextView mToolbarTitle;
    private AppBarLayout mAppBarLayout;

    private RecyclerView mRvSheetTopicList;     //动漫列表

    private TextView mTvCollect;   //收藏按钮
    private ImageView mIvBg;       //背景图


    private static final String ARG_SHEET_ID = "sheet_id";
    private String mSheetId;
    private SheetInfoContract.ISheetInfoPresenter mPresenter;

    private SheetTopicDetailsFragment.ComicListAdapter mSheetComicAdapter; // 动漫列表适配器
    private List<IModel.IComicModel> mSheetComicList = new ArrayList<>(); // 漫单中的动漫数据集合
    private int mIsCollected = 0;

    public SheetTopicDetailsFragment() {
    }

    public static SheetTopicDetailsFragment newInstance(String sheetId) {
        SheetTopicDetailsFragment fragment = new SheetTopicDetailsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_SHEET_ID, sheetId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSheetId = getArguments().getString(ARG_SHEET_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View layoutView = inflater.inflate(R.layout.fragment_sheet_topic_details, container, false);
        initComponents(layoutView);
        new SheetInfoPresenter(this, Injection.provideSheetInfoRepository());
        return layoutView;
    }

    /**
     * 初始化控件
     *
     * @param layoutView 根布局
     */
    private void initComponents(View layoutView) {
        mTvTitle = (TextView) layoutView.findViewById(R.id.mTvSheetTopicTitle);
        mTvDesc = (TextView) layoutView.findViewById(R.id.mTvSheetTopicDetailsContent);
        mTvInfo = (TextView) layoutView.findViewById(R.id.mTvSheetTopicAboutInfo);
        mIbBack = (ImageButton) layoutView.findViewById(R.id.mTvSheetTopicBack);
        mIbShare = (ImageButton) layoutView.findViewById(R.id.mTvSheetTopicShare);
        mIvBg = (ImageView) layoutView.findViewById(R.id.mTvSheetTopicBg);
        mTvCollect = (TextView) layoutView.findViewById(R.id.mTvSheetTopicCollect);
        mTintMask = layoutView.findViewById(R.id.tint_mask);
        mAppBarLayout = (AppBarLayout) layoutView.findViewById(R.id.mAbSheetTopicAppBar);
        mCollapsingToolbarLayout = (CollapsingToolbarLayout) layoutView.findViewById(R.id.mCtbSheetTopic);
        mToolbarTitle = (TextView) layoutView.findViewById(R.id.mTvSheetTopicToolbarTitle);

        mRvSheetTopicList = (RecyclerView) layoutView.findViewById(R.id.mRvSheetTopicList);

        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                // 注意：这里滑动多次调用，应该避免重复多次赋值
                if (verticalOffset == 0 && !mToolbarTitle.getText().toString().equals(getResources().getText(R.string.str_sheet_topic_details))) {
                    mToolbarTitle.setText(getResources().getText(R.string.str_sheet_topic_details));
                } else if (verticalOffset != 0 && mToolbarTitle.getText().toString().equals(getResources().getText(R.string.str_sheet_topic_details))) {
                    mToolbarTitle.setText(mTvTitle.getText());
                }
            }
        });

        mIbBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityHelper.INSTANCE.backActivity(getActivity());
            }
        });

        mIbShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, ShareHelper.generateShareText(mTvTitle.getText().toString(), mSheetId, ShareHelper.TYPE_SPECIAL));
                startActivity(intent);
            }
        });

        //收藏专题
        mTvCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //禁用收藏按钮
                mTvCollect.setEnabled(false);
                if (MyContract.Companion.getUSER_ID() != null) {
                    mPresenter.collectSheet(SheetInfoPresenter.Companion.getTYPE_TOPIC(), mSheetId, 1 - mIsCollected);
                } else {
                    Intent intent = new Intent(getActivity(), SingleActivity.class);
                    intent.putExtra(SingleActivity.Companion.getEXTRA_NAME(), SingleActivity.Companion.getINTENT_EXTRA_LOGIN());
                    ActivityHelper.INSTANCE.startActivity(getActivity(), intent);
                }
            }
        });

    }

    @Override
    public void initData() {

    }

    @Override
    public void bindData() {
        mSheetComicAdapter = new SheetTopicDetailsFragment.ComicListAdapter(getActivity(), mSheetComicList);
        mRvSheetTopicList.setAdapter(mSheetComicAdapter);
        mRvSheetTopicList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRvSheetTopicList.addOnScrollListener(new LoadMoreRecyclerOnScrollListener(mRvSheetTopicList.getLayoutManager()) {
            @Override
            public void onLoadMore(int currentPage) {
                mPresenter.getSheetInfo(SheetInfoContract.ISheetInfoPresenter.Companion.getTYPE_TOPIC(), mSheetId, currentPage);
            }
        });
        mPresenter.getSheetInfo(SheetInfoContract.ISheetInfoPresenter.Companion.getTYPE_TOPIC(), mSheetId, 1);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void showSheetInfo(@NotNull IModel.ISheetModel sheetInfo) {
        SheetModel model = (SheetModel) sheetInfo;
        mTvTitle.setText(model.getMandanTitle());
        mIsCollected = model.getmIsCollected();
        switchCollectedStateIcon();
        String summary = model.getSummary() != null && model.getSummary().trim().length() > 0 ? model.getSummary() : "没有介绍";
        mTvDesc.setText(summary);
        mTvInfo.setText(model.getCreateTime() + " | " + model.getAnimeCount() + "个动漫 | " + model.getCollectCount() + "人收藏");
        if (model.getMandanImg() != null & model.getMandanImg().trim().length() > 0) {
            Glide.with(getActivity()).load(model.getMandanImg()).asBitmap().into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    mIvBg.setImageBitmap(resource);
                    Palette.from(resource).generate(new Palette.PaletteAsyncListener() {
                        @Override
                        public void onGenerated(Palette palette) {
                            int color = palette.getDarkMutedColor(Color.parseColor("#000000"));
                            float[] colorHSV = new float[3];
                            Color.colorToHSV(color, colorHSV);
                            colorHSV[2] = colorHSV[2] - 0.1f < 0.1f ? colorHSV[2] : colorHSV[2] - 0.1f;
                            int darknessColor = Color.HSVToColor(colorHSV);
                            mTintMask.setBackgroundTintList(new ColorStateList(new int[][]{{0}}, new int[]{darknessColor}));
                            mRvSheetTopicList.setBackgroundColor(darknessColor);
                            mCollapsingToolbarLayout.setContentScrimColor(color);
                        }
                    });
                }
            });
        }
        mSheetComicList.clear();
        mSheetComicList.addAll(model.getmMandaList());
        mSheetComicAdapter.notifyDataSetChanged();
    }

    /**
     * 切换收藏按钮的状态
     */
    private void switchCollectedStateIcon() {
        if (mIsCollected == 1)
            mTvCollect.setText("已收藏专题");
        else
            mTvCollect.setText("收藏专题");
    }

    @Override
    public void showMoreSheetInfo(@NotNull IModel.ISheetModel sheetInfo) {
        SheetModel model = (SheetModel) sheetInfo;
        mSheetComicList.addAll(model.getmMandaList());
        mSheetComicAdapter.notifyDataSetChanged();
    }

    @Override
    public void showCollectSucceed() {
        mIsCollected = 1 - mIsCollected;
        switchCollectedStateIcon();
        mTvCollect.setEnabled(true);
        ToastHelper.getInstance(getActivity()).showSucceed("操作成功");
    }

    @Override
    public void showCollectFailed() {
        mTvCollect.setEnabled(true);
        ToastHelper.getInstance(getActivity()).showSucceed("操作失败");
    }

    @Override
    public void setPresenter(SheetInfoContract.ISheetInfoPresenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @NotNull
    @Override
    public Context getViewContext() {
        return getActivity();
    }

    @Override
    public void showNoNetwork() {
        ToastHelper.getInstance(getActivity()).showSucceed("没有网络");
    }

    @Override
    public void showRefreshFailed() {
        ToastHelper.getInstance(getActivity()).showError(getString(R.string.str_refresh_failed));
    }

    @Override
    public void showDeleteComicsState(boolean b) {
        // 不需要实现
    }

    /**
     * 列表适配器
     */
    private class ComicListAdapter extends UsedAdapter<ComicListViewHolder> {
        private Context mContext;
        private List<IModel.IComicModel> mData;

        public ComicListAdapter(Context context, List<IModel.IComicModel> data) {
            mContext = context;
            mData = data;
        }

        @NotNull
        @Override
        public ComicListViewHolder onCreateVH() {
            return new SheetTopicDetailsFragment.ComicListViewHolder(View.inflate(mContext, R.layout.item_comic_list_dark, null));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindVH(@NotNull ComicListViewHolder holder, int position) {
            final ComicModel model = (ComicModel) mData.get(position);
            Glide.with(mContext)
                    .load(model.getImgUrl())
                    .bitmapTransform(new CenterCrop(mContext), new GlideRoundTransform(mContext, 2))
                    .into(holder.mCover);

            holder.mTitle.setText(model.getTitle() + "(" + model.getYear() + ")");
            holder.mSubtitle.setText("更新至" + model.getEpisodes() + "集");
            holder.mThirdTitle.setText(model.getGenre());
            holder.mInfoLeft.setText(model.getCountry());
            holder.mInfoRight.setText(model.getRateScore());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, SingleActivity.class);
                    intent.putExtra(SingleActivity.Companion.getEXTRA_NAME(), SingleActivity.Companion.getINTENT_EXTRA_ANIME_INFO());
                    intent.putExtra(SingleActivity.Companion.getBUNDLE_EXTRA_KEY_ID(), model.getId());
                    ActivityHelper.INSTANCE.startActivity((Activity) mContext, intent);
                }
            });
        }

        @Override
        public int getDataTotal() {
            return mData.size();
        }
    }

    private class ComicListViewHolder extends UsedAdapter.UsedViewHolder {
        ImageView mCover;
        TextView mTitle;
        TextView mSubtitle;
        TextView mThirdTitle;
        TextView mInfoLeft;
        TextView mInfoRight;

        ComicListViewHolder(View itemView) {
            super(itemView);
            mCover = (ImageView) itemView.findViewById(R.id.mIvComicListCover);
            mTitle = (TextView) itemView.findViewById(R.id.mTvComicListTitle);
            mSubtitle = (TextView) itemView.findViewById(R.id.mTvComicListSubTitle);
            mThirdTitle = (TextView) itemView.findViewById(R.id.mTvComicListThirdTitle);
            mInfoLeft = (TextView) itemView.findViewById(R.id.mTvComicListLastWatchEpisode);
            mInfoRight = (TextView) itemView.findViewById(R.id.mTvComicListWatchTime);
        }
    }
}
